﻿using System;
using System.Configuration;
using System.Drawing;
using System.Windows.Forms;
using SDRdCard;

namespace GatewayInspect
{
    public class IDCradReader
    {
        #region Singleton

        private static IDCradReader _instance;
        private static object _lock = new object();

        private IDCradReader()
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            string strInterval = config.AppSettings.Settings["IDCardInterval"].Value;
            try
            {
                _interval = Convert.ToInt32(strInterval);
            }
            catch
            {
                _interval = 500;
            }
        }

        public static IDCradReader GetInstance()
        {
            if (_instance == null)
            {
                lock (_lock)
                {
                    if (_instance == null)
                    {
                        _instance = new IDCradReader();
                    }
                }
            }
            return _instance;
        }

        #endregion

        private Timer _timer;
        private int _interval = 500;
        private ISDRdCardX iReader = null;

        public delegate void AfterReadInfoHandler(CardInfo info);
        public event AfterReadInfoHandler AfterReadInfo;

        public void BeginRead()
        {
            try
            {
                if (iReader == null)
                {
                    iReader = new SDRdCardXClass();
                }
                int i = iReader.OpenPort();//打开端口连接设备
                if (i >= 0)//连接成功
                {
                    if (_timer == null)
                    {
                        _timer = new Timer();
                        _timer.Interval = _interval;
                        _timer.Tick += new EventHandler(_timer_Tick);
                    }
                    if (!_timer.Enabled)
                    {
                        _timer.Enabled = true;
                    }
                }
                else if (i == -5)//软件授权文件错误或没有授权文件
                {
                    MessageBox.Show("读卡器软件未授权！");
                }
                else
                {
                    MessageBox.Show("连接身份证读卡器失败:" + i);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("连接身份证读卡器失败:" + ex.Message);
            }
        }

        public void EndRead()
        {
            if (_timer != null && _timer.Enabled)
            {
                _timer.Enabled = false;
            }
            if (iReader != null)
            {
                iReader.ClosePort();
                iReader.DeleteAllPicture();
                iReader.DeleteOutputFile();
            }
        }

        /// <summary>
        /// 无对象实例需读卡(挂接AfterReadInfo事件)时停止读卡
        /// </summary>
        public void CheckHandler()
        {
            if (AfterReadInfo == null || AfterReadInfo.GetInvocationList().Length <= 0)
            {
                EndRead();
            }
        }

        private void _timer_Tick(object sender, EventArgs e)
        {
            if (iReader == null)
                return;

            if (iReader.ReadCard() >= 0 && iReader.bHaveCard)
            {
                CardInfo info = new CardInfo();
                info.Name = iReader.NameL;
                info.Sex = iReader.SexL;
                info.Nation = iReader.NationL;
                info.Birthday = iReader.BornL;
                info.Address = iReader.Address;
                info.CardNo = iReader.CardNo;
                info.StartDate = ToDateString(iReader.ActivityFrom);
                info.EndDate = ToDateString(iReader.ActivityTo);
                info.ArrPhotoByte = ImageToByteArray(iReader.PhotoPath);

                if (info != null && AfterReadInfo != null)
                {
                    AfterReadInfo(info);
                }
            }
        }

        /// <summary>
        /// 格式化日期字符串
        /// </summary>
        /// <param name="_date"></param>
        /// <returns></returns>
        private string ToDateString(string _date)
        {
            if (!string.IsNullOrEmpty(_date) && _date.Length == 8)
            {
                return string.Format("{0}年{1}月{2}日", _date.Substring(0, 4), _date.Substring(4, 2), _date.Substring(6, 2));
            }
            return string.Empty;
        }

        /// <summary>
        /// 将图片转换成字节
        /// </summary>
        /// <param name="selectPictureFile"></param>
        /// <returns></returns>
        private static Byte[] ImageToByteArray(string selectPictureFile)
        {
            Image photo = new Bitmap(selectPictureFile);
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            photo.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            byte[] imagedata = ms.GetBuffer();

            ms.Close();
            ms.Dispose();
            photo.Dispose();
            return imagedata;
        }
    }

    /// <summary>
    /// 身份证的信息
    /// </summary>
    public class CardInfo
    {
        /// <summary>
        /// 身份证号码
        /// </summary>
        public string CardNo;

        /// <summary>
        /// 姓名
        /// </summary>
        public string Name;

        /// <summary>
        /// 性别
        /// </summary>
        public string Sex;

        /// <summary>
        /// 出生日期
        /// </summary>
        public string Birthday;

        /// <summary>
        /// 地址
        /// </summary>
        public string Address;

        /// <summary>
        /// 证件开始日期
        /// </summary>
        public string StartDate;

        /// <summary>
        /// 证件结束日期
        /// </summary>
        public string EndDate;

        /// <summary>
        /// 民族
        /// </summary>
        public string Nation;

        /// <summary>
        /// 相片的字节信息
        /// </summary>
        public byte[] ArrPhotoByte;
    }
}
